package com.thinking.walle.cf.taste.web;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.recommender.Recommender;

/**
 * <p>A singleton which holds an instance of a {@link Recommender}. This is used to share
 * a {@link Recommender} between {@link RecommenderServlet} and <code>RecommenderService.jws</code>.</p>
 */
public final class RecommenderSingleton {

    private final Recommender recommender;

    private static RecommenderSingleton instance;

    public static synchronized RecommenderSingleton getInstance() {
        if (instance == null) {
            throw new IllegalStateException("Not initialized");
        }
        return instance;
    }

    public static synchronized void initializeIfNeeded(String recommenderClassName) throws TasteException {
        if (instance == null) {
            instance = new RecommenderSingleton(recommenderClassName);
        }
    }

    private RecommenderSingleton(String recommenderClassName) throws TasteException {
        if (recommenderClassName == null) {
            throw new IllegalArgumentException("Recommender class name is null");
        }
        try {
            recommender = Class.forName(recommenderClassName).asSubclass(Recommender.class).newInstance();
        } catch (ClassNotFoundException cnfe) {
            throw new TasteException(cnfe);
        } catch (InstantiationException ie) {
            throw new TasteException(ie);
        } catch (IllegalAccessException iae) {
            throw new TasteException(iae);
        }
    }

    public Recommender getRecommender() {
        return recommender;
    }

}